﻿using lwzlz.Core;
using lwzlz.Web.Areas.SysAdmin.Controllers;
using lwzlz.Web.Areas.SysAdmin.Models;
using lzwlz.Web;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Web.Mvc;
using Font = System.Drawing.Font;
using Drawing = System.Drawing;
using IO = System.IO;
using Web1 = System.Web;
using System.Drawing.Text;

namespace lwzlz.Web.Areas.Mall.Controllers
{
    public class StickerController : MallController
    {
        #region 界面
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            return View();
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult Edit(string id = "")
        {
            var model = new Sticker();

            if (!string.IsNullOrWhiteSpace(id) && int.TryParse(id, out int idInt))
            {
                model = new Application.System.StickerService().Get(idInt);
            }
            else
            {
                var memberId = MallMemberLogin.GetCurrentUser().Id.ToString();
                var sticker = new Application.System.StickerService().GetLastTop1(int.Parse(memberId));
                if (sticker != null)
                {
                    model.QRCode = sticker.QRCode;
                }
            }

            return View(model);
        }
        #endregion

        #region 接口
        /// <summary>
        /// 姓名贴列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult StickerList(int pageNumber, int pageSize, string keyword = null)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var stickerService = new Application.System.StickerService();
                var dic = new Dictionary<string, string>();
                //会员ID
                {
                    dic.Add("MemberId", MallMemberLogin.GetCurrentUser().Id.ToString());
                }
                //关键词
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    dic.Add("Name", keyword);
                }

                var list = stickerService.GetListPage(pageNumber, pageSize, dic, null, null, out int count);

                response.Data = new { List = list, Count = count, };
                response.Success = true;
                response.Message = "获取成功";
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="UserName"></param>
        /// <param name="PassWord"></param>
        /// <param name="RealName"></param>
        /// <param name="Status"></param>
        /// <param name="MemberId"></param>
        /// <returns></returns>
        public JsonResult Save(string Id, string Name, string Remark, string QRCode, string MemberId)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var stickerService = new Application.System.StickerService();
                if (!string.IsNullOrWhiteSpace(Id) && int.TryParse(Id, out int id) && id > 0)
                {
                    var entity = stickerService.Get(id);
                    entity.Name = Name;
                    entity.Remark = Remark;
                    entity.QRCode = QRCode;
                    entity.LastModificationTime = DateTime.Now;
                    entity.Url = DrawingSticker(entity);
                    var result = stickerService.Update(entity, null);
                    if (result > 0)
                    {
                        response.Success = true;
                        response.Message = "保存成功";
                        response.Data = entity;
                    }
                    else
                    {
                        throw new Exception("保存失败");
                    }
                }
                else
                {
                    var entity = new Sticker()
                    {
                        Name = Name,
                        Remark = Remark,
                        QRCode = QRCode,
                        MemberId = int.Parse(MemberId),
                        CreationTime = DateTime.Now
                    };
                    entity.Url = DrawingSticker(entity);
                    var result = stickerService.Insert(entity, null);
                    if (result.HasValue && result.Value > 0)
                    {
                        response.Success = true;
                        response.Message = "保存成功";
                        response.Data = entity;
                    }
                    else
                    {
                        throw new Exception("保存失败");
                    }
                }
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }

        /// <summary>
        /// 删除姓名贴
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteSticker(string id)
        {
            ResponseModel response = new ResponseModel();
            try
            {
                var stickerService = new Application.System.StickerService();
                stickerService.DeleteList(id.ToString());
                response.Success = true;
                response.Message = "删除成功";
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
            }
            return Json(response);
        }
        #endregion

        /// <summary>
        /// 上传二维码
        /// </summary>
        /// <returns></returns>
        public JsonResult UpLoadQrCodePic()
        {
            var fs = Request.Files[0];
            return Json(new FileController().UpLoad($"/upload/qrCode/", fs));
        }

        /// <summary>
        /// 绘制
        /// </summary>
        /// <param name="sticker"></param>
        /// <returns></returns>
        public string DrawingSticker(Sticker sticker)
        {
            string baseUrl = Request.MapPath("~/Areas/Mall/image/sticker.jpg");
            string qrCodeUrl = Request.MapPath(sticker.QRCode);
            var vpath = "/upload/sticker/" + DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/";
            var fileName = Guid.NewGuid().ToString() + ".jpg";
            using (Image baseImage = Image.FromFile(baseUrl))
            {
                using (Image qrCodeImg = Image.FromFile(qrCodeUrl))
                {
                    using (Graphics g = Graphics.FromImage(baseImage))
                    {
                        int x = baseImage.Width - qrCodeImg.Width;
                        int y = baseImage.Height - qrCodeImg.Height;
                        //添加二维码
                        g.DrawImage(qrCodeImg, 3326, 975, 1160, 1160);

                        //字体颜色
                        SolidBrush drawBushBlack = new SolidBrush(Color.Black);
                        SolidBrush drawBushGray = new SolidBrush(Color.Gray);
                        //从外部文件加载字体文件  
                        PrivateFontCollection font = new PrivateFontCollection();
                        font.AddFontFile(Web1.HttpContext.Current.Server.MapPath("~/Content/font/方正硬笔楷书_GBK.ttf"));
                        //检测字体类型是否可用
                        var r = font.Families[0].IsStyleAvailable(FontStyle.Regular);
                        var b = font.Families[0].IsStyleAvailable(FontStyle.Bold);
                        //定义成新的字体对象
                        FontFamily myFontFamily = new FontFamily(font.Families[0].Name, font);
                        Font drawFontFirst = new Font(myFontFamily, 28, GraphicsUnit.Millimeter);
                        Font drawFontSecond = new Font(myFontFamily, 13, GraphicsUnit.Millimeter);
                        //写姓名
                        char[] nameCharArr = sticker.Name.ToCharArray();
                        //姓名框

                        //横排
                        //默认X坐标
                        var firstNameX = 442;
                        //默认Y坐标
                        var firstNameY = 993;
                        //偏移量
                        var firstNameDev = 710;
                        for (int i = 0; i < nameCharArr.Length; i++)
                        {
                            g.DrawString(nameCharArr[i].ToString(), drawFontFirst, drawBushBlack, firstNameX, firstNameY);
                            firstNameX += firstNameDev;
                        }

                        //竖排
                        //默认Y坐标
                        var secondNameY = 2512;
                        //Y偏移量
                        var secondNameYDev = 352;
                        //X偏移量
                        var secondNameXDev = 354;
                        //名字循环
                        for (int j = 0; j < nameCharArr.Length; j++)
                        {
                            //默认X坐标
                            var secondNameX = 508;
                            //格子循环
                            for (int k = 0; k < 11; k++)
                            {
                                if (k == 0)
                                {
                                    g.DrawString(nameCharArr[j].ToString(), drawFontSecond, drawBushBlack, secondNameX, secondNameY);
                                }
                                else
                                {
                                    g.DrawString(nameCharArr[j].ToString(), drawFontSecond, drawBushGray, secondNameX, secondNameY);
                                }
                                secondNameX += secondNameXDev;
                            }
                            secondNameY += secondNameYDev;
                        }

                        //写备注
                        //默认Y坐标
                        var remarkY = 3826;
                        //X偏移量
                        var remarkXDev = 354;
                        //Y偏移量
                        var remarkYDev = 352;
                        char[] remarkCharArr = sticker.Remark.ToCharArray();
                        //格子竖向循环
                        for (int j = 0; j < 8; j++)
                        {
                            //默认X坐标
                            var remarkX = 508;
                            //格子横向循环
                            for (int l = 0; l < remarkCharArr.Length; l++)
                            {
                                if (j == 0)
                                {
                                    g.DrawString(remarkCharArr[l].ToString(), drawFontSecond, drawBushBlack, remarkX, remarkY);
                                }
                                else
                                {
                                    g.DrawString(remarkCharArr[l].ToString(), drawFontSecond, drawBushGray, remarkX, remarkY);
                                }
                                remarkX += remarkXDev;
                            }
                            remarkY += remarkYDev;
                        }

                        //保存
                        string physicalPath = Web1.HttpContext.Current.Server.MapPath("~" + vpath);
                        if (!IO.Directory.Exists(physicalPath))
                        {
                            IO.Directory.CreateDirectory(physicalPath);
                        }
                        string filePath = Path.Combine(physicalPath, fileName);
                        baseImage.Save(filePath, Drawing.Imaging.ImageFormat.Jpeg);
                        if (IO.File.Exists(filePath))
                        {
                            return vpath + fileName;
                        }
                        else
                        {
                            return null;
                        }
                    }
                }
            }
        }
    }
}